package handlers

import (
	"MBTIx/auth"
	"MBTIx/dba"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/jmoiron/sqlx"
)

func AuthHandler(c *gin.Context) {
	var user auth.User
	err := c.ShouldBind(&user)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 2001,
			"msg":  "无效参数",
		})
		return
	}
	if user.Correct() {
		tokenString, _ := auth.GenToken(user.Name)
		c.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  "success",
			"data": gin.H{"accessToken": tokenString},

			
		})
		return
	}

	db, _ := c.Get("db")
	var password string
	dba.GetPassword(db.(*sqlx.DB), user.Name, &password)
	if password == user.Password {
		tokenString, _ := auth.GenToken(user.Name)
		c.JSON(http.StatusOK, gin.H{
			"code": 20000,
			"msg":  "success",
			"data": gin.H{"accessToken": tokenString},
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 2002,
		"msg":  "鉴权失败",
	})
}

func Info(c *gin.Context) {
	username, _ := c.Get("username")

	c.JSON(http.StatusOK, gin.H{
		"code": 20000,
		"msg":  "success",
		"data": gin.H{
			"user": auth.UserInfo{
				Name:  username.(string),
				Roles: []string{"admin"},
			},
		},
	})
}
